<?php
/**
 * Hello Model for Hello World Component
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 * @link http://dev.joomla.org/component/option,com_jd-wiki/Itemid,31/id,tutorials:modules/
 * @license		GNU/GPL
 */

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

jimport( 'joomla.application.component.model' );
//jimport( 'joomla.application.component.helper' );

/**
 * Hello Model
 *
 * @package    Joomla.Tutorials
 * @subpackage Components
 */
class JBSModelUsers extends JModel
{
	/**
	 * EventTypes data array
	 *
	 * @var array
	 */
	public $_data = null;

	/**
	 * Events total
	 *
	 * @var integer
	 */
	public $_total = null;

	/**
	 * Pagination object
	 *
	 * @var object
	 */
	public $_pagination = null;


	function __construct()
	{
		parent::__construct();
		global $mainframe, $option;

		$limit		= $mainframe->getUserStateFromRequest( $option.'limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
		$limitstart = $mainframe->getUserStateFromRequest( $option.'limitstart', 'limitstart', 0, 'int' );

		$this->setState('limit', $limit);
		$this->setState('limitstart', $limitstart);

		$array = JRequest::getVar('cid',  0, '', 'array');
		$this->setId((int)$array[0]);
	}

	/**
	 * Method to get event types item data
	 *
	 * @access public
	 * @return array
	 */
	function getDataList()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_data))
		{
			$query = $this->_buildQuery();
			//echo $query;
			$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
		}
		//print_r($this->_data);

		return $this->_data;
	}

	/**
	 * Total nr of eventtypes
	 *
	 * @access public
	 * @return integer
	 */
	function getTotal()
	{
		// Lets load the total nr if it doesn't already exist
		if (empty($this->_total))
		{
			$query = $this->_buildQuery();
			$this->_total = $this->_getListCount($query);
		}

		return $this->_total;
	}

	/**
	 * Method to get a pagination object for the groups
	 *
	 * @access public
	 * @return integer
	 */
	function getPagination()
	{
		// Lets load the content if it doesn't already exist
		if (empty($this->_pagination))
		{
			jimport('joomla.html.pagination');
			$this->_pagination = new JPagination( $this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
		}

		return $this->_pagination;
	}

	/**
	 * Build the query
	 *
	 * @access private
	 * @return string
	 */
	function _buildQuery()
	{
		// Get the WHERE and ORDER BY clauses for the query
		$where		= $this->_buildContentWhere();
		$orderby	= $this->_buildContentOrderBy();

		$query = "SELECT " .
					"ju.system_user_id AS id, " .
					"u.username, " .
					"u.name, " .
					"u.usertype, " .
					"u.email, " .
					"r.id AS 'tsb_role_id', " .
					"r.name AS 'tsb_role' " .
					"FROM " .
					"#__jbschedule_users ju " .
					"Inner Join #__users u ON ju.system_user_id = u.id " .
					"Inner Join #__jbschedule_roles r ON r.id = ju.tsb_role_id "
					. $where
					. $orderby
					;
//		echo $query;
		return $query;
	}

	/**
	 * Build the order clause
	 *
	 * @access private
	 * @return string
	 */
	function _buildContentOrderBy()
	{
		global $mainframe, $option;
		$nameField  = 'u.name';

		$filter_order		= $mainframe->getUserStateFromRequest( $option.'.users.filter_order', 'filter_order',$nameField, 'cmd' );
		$filter_order_Dir	= $mainframe->getUserStateFromRequest( $option.'.users.filter_order_Dir', 'filter_order_Dir', '', 'word' );


		$orderby 	= ' ORDER BY '.$filter_order.' '.$filter_order_Dir.', '.$nameField;

		return $orderby;
	}

	/**
	 * Build the where clause
	 *
	 * @access private
	 * @return string
	 */
	function _buildContentWhere()
	{
		global $mainframe, $option;

		$search 			= $mainframe->getUserStateFromRequest( $option.'.search', 'search', '', 'string' );
		$search 			= $this->_db->getEscaped( trim(JString::strtolower( $search ) ) );

		$where = array();
		// u.name là filed trong db
		$where[] = ' LOWER(u.name) LIKE \'%'.$search.'%\' ';

		$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );

		return $where;
	}

	/**
	 * Method to set the hello identifier
	 *
	 * @access	public
	 * @param	int Hello identifier
	 * @return	void
	 */
	function setId($id)
	{
		// Set id and wipe data
		$this->_id		= $id;
		$this->_data	= null;
	}

	function &getAllData()
	{
		// Load all data
//		if (empty( $this->_data )) {
			$query = "SELECT " .
					"#__jbschedule_users.system_user_id AS id, " .
					"#__users.username, " .
					"#__users.name, " .
					"#__users.usertype, " .
					"#__users.email, " .
					"#__jbschedule_roles.id AS 'tsb_role_id', " .
					"#__jbschedule_roles.name AS 'tsb_role' " .
					"FROM " .
					"#__jbschedule_users " .
					"Inner Join #__users ON #__jbschedule_users.system_user_id = #__users.id " .
					"Inner Join #__jbschedule_roles ON #__jbschedule_roles.id = #__jbschedule_users.tsb_role_id " .
					"ORDER BY #__users.username";

			$this->_data = $this->_getList( $query );

			//$this->_db->setQuery( $query );
			//$this->_data = $this->_db->loadObjectList();
//		}
		if (!$this->_data) {
			$this->_data = null;
		}
		return $this->_data;
	}

	/**
	 * Method to get a hello
	 * @return object with data
	 */
	function &getData()
	{
		// Load the data
		if (empty( $this->_data )) {
			$query = "SELECT " .
					"#__users.username, " .
					"#__users.name, " .
					"#__users.usertype, " .
					"#__users.email, " .
					"#__jbschedule_roles.name as 'tsb_role', " .
					"#__jbschedule_roles.id as 'tsb_role_id', " .
					"#__jbschedule_users.system_user_id as 'id' " .
					"FROM " .
					"#__jbschedule_users " .
					"Inner Join #__users ON #__jbschedule_users.system_user_id = #__users.id " .
					"Inner Join #__jbschedule_roles ON #__jbschedule_roles.id = #__jbschedule_users.tsb_role_id " .
					"WHERE #__jbschedule_users.system_user_id = " . $this->_id;

			$this->_db->setQuery( $query );
			$this->_data = $this->_db->loadObject();
		}
		if (!$this->_data) {
			$this->_data = new stdClass();
			$this->_data->id = 0;
			$this->_data->name = null;
			$this->_data->username = null;
			$this->_data->email = null;
			$this->_data->tsb_role = null;
			$this->_data->usertype = null;
		}
		return $this->_data;
	}

	/**
	 * Method to store a record
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function store()
	{
		$data = JRequest::get( 'post' );

		$query = "SELECT * FROM #__jbschedule_users WHERE system_user_id = '". $data[id] ."'";
		$this->_db->setQuery( $query );
		$exists = $this->_db->loadObject();

		//Neu da co ban ghi nay trong table #__jbschedule_users thuc hien UPDATE
		if($exists != null){
			$query = "UPDATE #__jbschedule_users SET tsb_role_id = '" . $data[tsb_role_id] . "' " .
					"WHERE system_user_id = '" . $data[id] . "'";
			if (!$this->_db->execute($query)) {
				$this->setError( $row->getErrorMsg() );
				return false;
			}
		}//Neu chua co ban ghi nay trong table #__jbschedule_users thuc hien INSERT
		else{
			$query = "INSERT INTO #__jbschedule_users VALUES('" . $data[id] . "', '" . $data[tsb_role_id] . "')";
			if (!$this->_db->execute($query)) {
				$this->setError( $row->getErrorMsg() );
				return false;
			}
		}
		return true;
	}

	/**
	 * Method to delete record(s)
	 *
	 * @access	public
	 * @return	boolean	True on success
	 */
	function delete()
	{
		$cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

		/*if(!$this->isDeleteable($cids)){
			$this->setError( JText::_('CAN NOT DELETE ADMINISTRATOR ACCOUNT') );
			return false;
		}*/

		$row =& $this->getTable();

		if (count( $cids ))
		{
			foreach($cids as $cid) {
				if (!$row->delete( $cid )) {
					$this->setError( $row->getErrorMsg() );
					return false;
				}
			}
		}
		return true;
	}
	/*
	function deleteJBSUser($id){
		$query = "UPDATE #__jbschedule_users SET role_id = null";
	}
*/
	function getAllSystemUsers(){
		$query = "SELECT * " .
				"FROM " .
				"#__users " .
				"WHERE #__users.id NOT IN (SELECT #__jbschedule_users.system_user_id FROM #__jbschedule_users)";

		$this->_data = $this->_getList( $query );
		if (!$this->_data) {
			$this->_data = null;
		}
		return $this->_data;
	}

	/*
	 * Check if the user to be deleted is Administrator or not
	 * */
	function isDeleteable($id){
		$query = "SELECT r.is_super_admin " .
				"FROM jos_jbschedule_users u Inner Join jos_jbschedule_roles r ON r.id = u.tsb_role_id " .
				"WHERE jos_jbschedule_users.system_user_id =  '".$id."' AND r.is_super_admin = '1'";

		return ! $this->_getListCount() > 0;
	}
}
